﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows.Data;
using TciNewsReader_2014_04.VmHelpers;
namespace TciNewsReader_2014_04
{
    public partial class ViewModel
    {
        public ObservableCollection<CrudWrapper> CrudWrappers { get; private set; }
        private ListCollectionView _feedCrudListCollectionView;
        private List<NotifyCollectionChangedEventArgs> _crudNotifyCollectionChangedEventArgs = new List<NotifyCollectionChangedEventArgs>(); 
        private void InitialiseFeedCruds()
        {
            CrudWrappers = new ObservableCollection<CrudWrapper>();
            _feedCrudListCollectionView = CollectionViewSource.GetDefaultView(CrudWrappers) as ListCollectionView;
            if (_feedCrudListCollectionView != null)
            {
                _feedCrudListCollectionView.IsLiveFiltering = true;
                _feedCrudListCollectionView.IsLiveSorting = true;
            }
        }
        void CrudWrappers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            _crudNotifyCollectionChangedEventArgs.Add(e);
            if (e.Action == NotifyCollectionChangedAction.Reset) return;
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (CrudWrapper cw in e.NewItems)
                {
                    cw.State = CrudState.Created;
                }
            }
        }
        private void PopulateFeedCruds(List<string> urls)
        {
            _feedCrudListCollectionView.Dispatcher.Invoke(() =>
            {
                CrudWrappers.CollectionChanged -= CrudWrappers_CollectionChanged;
                CrudWrappers.Clear();
                urls.ForEach(q =>
                {
                    CrudWrapper cw = new CrudWrapper{Url = q};
                    _feedCrudListCollectionView.AddNewItem(cw);
                });
                _feedCrudListCollectionView.CommitNew();
                CrudWrappers.CollectionChanged += CrudWrappers_CollectionChanged;
            });
        }
    }
}
